package com.zxq.ruoyi.network.tcp.handler.impl;

import com.zxq.ruoyi.network.tcp.cache.TcpChannelCache;
import com.zxq.ruoyi.network.tcp.handler.dispatch.TCPDispatchHandler;
import com.zxq.ruoyi.network.tcp.handler.impl.modbus.AbsModbusRegister;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public  class TCPModbusPoxyHandler extends TCPDispatchHandler {


    /**
     * modbus 注册处理器
     */
    public static ConcurrentHashMap<String, AbsModbusRegister> frameRegister = new ConcurrentHashMap<>();

    /**
     * 设备对应的modbus处理器
     */
    public static ConcurrentHashMap<String, AbsModbusRegister> devRegister = new ConcurrentHashMap<>();





    @SneakyThrows
    @Override
    public boolean isThisFrame() {
         while (in.readableBytes() < 4) {
             Thread.sleep(10);
         }
         // 注册帧 FF 0000000001 FF
         // tcp-modbus协议 00 00 00 00 00 06 01 03 00 00 00 0A
         Short transactionId = in.readShort();
         Short protocolId = in.readShort();
         String headKey = String.format("%04x%04x",transactionId,protocolId);
         log.info(String.format("tcp-modbus headKey:%s",headKey));
         String devId = TcpChannelCache.getDevId(channel);
         if(StringUtils.isEmpty(devId)) {
             log.info("tcp-modbus devId not allow empty");
             return false;
         }
         log.info(String.format("devId:%s check tcp-modbus",devId));
         AbsModbusRegister absModbusRegister = devRegister.get(devId);
         if(absModbusRegister != null){
             log.info(String.format("devId:%s use tcp-modbus protocol",devId));
             return true;
         }
         absModbusRegister = frameRegister.get(headKey);

         if(absModbusRegister != null){
             log.info(String.format("devId:%s use tcp-modbus protocol",devId));
             devRegister.put(devId,absModbusRegister);
             return true;
         }
         log.info(String.format("devId:%s not use tcp-modbus",devId));
         return false;
    }


    @Override
    protected Boolean isRegisterFrame() {
        return false;
    }
    // 注册帧 FF0000000001FF
    // 发送 000000000006 010300000002
    // 接收 000000000006 0103040292FF9B
    @SneakyThrows
    @Override
    protected byte[] trimFrame() {
        while (in.readableBytes() < 6 ) {
            Thread.sleep(10);
        }
        in.readShort();
        in.readShort();
        Short len = in.readShort();
        while (in.readableBytes() < len) {
            Thread.sleep(10);
        }
        Integer totalSize = 6 + len;
        byte[] frame = new byte[totalSize];
        in.resetReaderIndex();
        in.readBytes(frame);
        return frame;
    }



}
